<template>
<div class="resetBack">
<div class="resetCss">
  <div class="resetTitle">重置密码</div>
  <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" label-position="right">
    <el-form-item label="手机号" prop="tel">
      <el-input v-model.number="ruleForm.tel" autocomplete="off" :prefix-icon="Iphone"/>
    </el-form-item>
    <el-form-item label="验证码" prop="code">
      <div style="display: flex;">
        <div><el-input v-model.number="ruleForm.code" autocomplete="off" :prefix-icon="SuccessFilled"></el-input></div>
        <el-button type="warning" :loading="checkCodeBtn.loading" :disabled="checkCodeBtn.disabled" @click="getResetCaptcha(ruleFormRef)" style="margin-left: 5px;">{{checkCodeBtn.text}}</el-button>
      </div>      
    </el-form-item>
    <el-form-item label="旧密码" prop="oldPassword">
      <el-input v-model.trim="ruleForm.oldPassword" type="password" autocomplete="off" show-password  :prefix-icon="Lock" />
    </el-form-item>
    <el-form-item label="新密码" prop="newPassword">
      <el-input v-model.trim="ruleForm.newPassword" type="password" autocomplete="off" show-password  :prefix-icon="Lock" />
    </el-form-item>
    <el-form-item label="确认新密码" prop="checkPass">
      <el-input v-model.trim="ruleForm.checkPass" type="password" autocomplete="off"  show-password :prefix-icon="Lock"/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitResetForm(ruleFormRef)" style="width: 200px;margin-left: auto;margin-right: auto;">重置密码</el-button>
    </el-form-item>
  </el-form>
  </div>
</div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { Lock,Iphone,SuccessFilled } from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus'
import axios from 'axios'
import router from '@/router'

const ruleFormRef = ref()

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('Please input the password'))
  } else {
    if (ruleForm.checkPass !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('checkPass', () => null)
    }
    callback()
  }
}

const checkOld = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('Please input the old password'))
  } else {
    callback()
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('Please input the password again'))
  } else if (value !== ruleForm.newPassword) {
    callback(new Error("Two inputs don't match!"))
  } else {
    callback()
  }
}
const checktelephone = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('Please input the phone'))
  }else if(value.length!=11) { 
           alert('请输入有效的手机号码，需是11位！');
            return false; 
  }else{
        callback();  
  }    	
}

const checkcaptcha = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入验证码'))
  }else{
        callback();
      }  	
}

let checkCodeBtn = reactive({
  text: "获取验证码",
  loading: false,
  disabled: false,
  duration: 100,
  timer: null,
})

const ruleForm = reactive({
  newPassword: '',
  checkPass: '',
  tel: '',
  code: '',
  oldPassword: '',
})

const rules = reactive({
  newPassword: [{ validator: validatePass, trigger: 'blur' }],
  checkPass: [{ validator: validatePass2, trigger: 'blur' }],
  tel: [{ validator: checktelephone, trigger: 'blur' }],
  code: [{ validator: checkcaptcha, trigger: 'blur' }],
  oldPassword: [{ validator: checkOld, trigger: 'blur' }],
})

const getResetCaptcha = async(formEl) => {
  // 手机号为空,就弹出提示框提示
  if(formEl.tel == ''){
    ElMessage({type: "error",message: "手机号不能为空"})
  }
      //向后端发送请求，获取验证码
      axios.get('/sms-service/sms/send/'+ruleForm.tel).then((res) => { 
        console.log("res是：")  
        console.log(res)
        if(res.code == 200){
          //弹窗短信发送成功
          ElMessage({
            message: '短信发送成功.',
            type: 'success',
         })
         //将button内容改变
         //倒计时期间按下按钮不能单击
         if(checkCodeBtn.duration !== 100){
          checkCodeBtn.disabled = true
         }
         //清除掉定时器
         checkCodeBtn.timer && clearInterval(checkCodeBtn.timer)
         //开启定时器
         checkCodeBtn.timer = setInterval(() => {
          const tmp = checkCodeBtn.duration--
          checkCodeBtn.text =  `${tmp}秒`
          if(tmp <= 0){
            //清除掉定时器
            clearInterval(checkCodeBtn.timer)
            checkCodeBtn.duration = 100
            checkCodeBtn.text = "重新获取"
            //设置按钮可以单击
            checkCodeBtn.disabled = false
          }
          console.info(checkCodeBtn.duration)
         },1000)

        }else{
          //弹窗短信发送失败
          ElMessage({
            message: '短信发送失败.',
            type: 'error',
         })
        }
     }).catch((err) => {

       console.log(err)

       })
    }

const submitResetForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log('submit!')
      axios.put('/account-service/admin/resetPassword',ruleForm).then((res) => {   
        console.log(res)
        if(res.code == 200){
          //重置成功
          ElMessage({type: "success",message: "重置成功"})
          router.push("/")
        }else{
          //重置失败
         ElMessage({type: "error",message: "重置失败"})
        }
      }).catch((err) => {

      console.log(err)

    })
    } else {
      console.log('error submit!')
      return false
    }
  })
}
</script>
<style scoped>
*{
  margin:0;
	padding:0;
	border:0
}
.resetBack{
  margin: 0;
  padding: 0;
  border: 0;
  position: fixed;
  width: 100%;
  height: 100%;
}
.resetBack .resetCss{
  margin-left: auto;
  margin-right: auto;
  width: 30%;
  margin-top: 13%;
}
.resetBack .resetCss .resetTitle{
  font-size: 30px;
  margin-left: 50%;
  font-weight: bolder;
  color: rgb(62, 72, 221);
}
</style>